package flappy.Game;

import com.badlogic.gdx.math.*;

import flappy.TienIch.ScrollHandler;
import flappy.VatThe.*;

public class GameWorld {
	
	public Chim       chim;
	ScrollHandler     scroller;
	private Rectangle ground;
	int               diem = 0;
	private float     t    = 0;
	public int        y;
	TrangThaiGame     TrangThai;
	
public	GameRenderer      renderer;
	boolean           daCapNhatLaiGiaoDien;
	
	public GameWorld(int midPointY) {
		daCapNhatLaiGiaoDien = true;
		
		TrangThai = TrangThaiGame.ChaoMung;
		this.y = midPointY;
		chim = new Chim(33, midPointY - 5, 17, 12);
		
		scroller = new ScrollHandler(this, midPointY + 66);
		ground = new Rectangle(0, midPointY + 66, 137, 11);
	}
	
	public void update(float delta) {
		t += delta;
		switch (TrangThai) {
			case SanSang:
			case ChaoMung:
				capNhatManHinhSanSang(delta);
				break;
			case DangChoi:
				capNhatManHinhChoiGame(delta);
				break;
			default:
				break;
		}
		
	}
	
	private void capNhatManHinhSanSang(float delta) {
		chim.nhapNho(t);
		scroller.updateReady(delta);
	}
	
	public void capNhatManHinhChoiGame(float delta) {
		if (delta > .15f) {
			delta = .15f;
		}
		
		chim.update(delta);
		scroller.update(delta);
		
		if (scroller.KiemTraVaCham(chim) && chim.ConSong) {
			scroller.stop();
			chim.Chet();
			TaiNguyen.amThanhVaCham.play();
			TaiNguyen.amThanhChet.play();
		}
		
		if (Intersector.overlaps(chim.bienVaCham, ground)) {
			
			if (chim.ConSong) {
				TaiNguyen.amThanhVaCham.play();
				chim.Chet();
			}
			
			scroller.stop();
			chim.DungLai();
			TrangThai = TrangThaiGame.GameOver;
			
			if (diem > TaiNguyen.LayDiemCaoNhat()) {
				TaiNguyen.CapNhatDiem(diem);
				TrangThai = TrangThaiGame.XemDiem;
			}
		}
	}
	
	public void CongDiem() {
		diem++;
	}
	
	public void batDau() {
		TrangThai = TrangThaiGame.DangChoi;
	}
	
	public void sanSang() {
		TrangThai = TrangThaiGame.SanSang;
		TaiNguyen.amThanhChaoMung.play();
	}
	
	public void khoiTaoLai() {
		renderer.KhoiTaoTaiNguyen();
		diem = 0;
		chim.KhoiTao(y - 5);
		scroller.onRestart();
		sanSang();
	}
	
}
